// src/api.js
import axios from 'axios';
import {getToken} from '@/apis/common';
import { Message } from '@arco-design/web-react';
const apiBaseUrl = 'http://127.0.0.1:8000'; // 替换为你的 API 地址

const api = axios.create({
  baseURL: apiBaseUrl,
  headers: {
    'Content-Type': 'application/json',
  },
});
axios.defaults.withCredentials = true;

// 添加请求拦截器
api.interceptors.request.use(
  (config) => {
    // 从全局状态中获取 access_token
    const accessToken = getToken();
    if (accessToken) {
      config.headers.Authorization = `Bearer ${accessToken}`;
    }
    return config;
  },
  (error) => {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
api.interceptors.response.use(
  (response) => {
    // 对响应数据做点什么
    if (response.data.status === 'success') {
      return response;
    } else if (response.data.status === 'error') {
      throw new Error(response.data.message);
    } else if (response.data.status === 'unauthorized') {
      throw new Error('未授权，请重新登录');
    }
    throw new Error('未知错误');
  },
  (error) => {
    // 对响应错误做点什么
    if (error.response) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      if (error.response.data.status === 'error') {
        Message.error("请求错误" + error.response.data.message);
        throw new Error(error.response.data.message);
      } else if (error.response.data.status === 'unauthorized') {
        Message.error("未授权，请重新登录");
        window.location.href = '/login';
      }
    }
    Message.error('网络请求失败' + error);
    throw error;
  }
);

export default api;